package com.walle.core.utils;

import com.walle.core.constants.Constants;
import com.walle.core.model.LoginUserInfo;
import com.walle.service.common.CacheProxy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

@Component
public class SessionUtil {

    @Resource
    private CacheProxy<String, LoginUserInfo> cacheProxy;

    /**
     * 获取令牌
     *
     * @param request HttpServletRequest
     * @return 登录令牌
     */
    public String getToken (HttpServletRequest request) {
        // 从cookie中获取
        for (Cookie cookie : request.getCookies()) {
            if (Constants.HEADER_TOKEN.equals(cookie.getName())) {
                return cookie.getValue();
            }
        }
        return request.getHeader(Constants.HEADER_TOKEN);
    }

    /**
     * 获取登录用户信息
     *
     * @param request HttpServletRequest
     * @return 登录用户信息
     */
    public LoginUserInfo getLoginUserInfo (HttpServletRequest request) {
        String token = this.getToken(request);
        if (token == null) {
            return null;
        }
        return cacheProxy.get(token);
    }
}
